package com.sctvcloud.pingwu.base;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentManager;
import android.text.TextUtils;
import android.widget.Toast;

import com.jiongbull.jlog.JLog;
import com.ruihang.generalibrary.ui.dialog.ShareFragment;
import com.ruihang.generalibrary.utils.IShares;
import com.ruihang.generalibrary.utils.ResultAsyncTask;
import com.ruihang.generalibrary.utils.TimeObserve;
import com.sctvcloud.pingwu.R;
import com.sctvcloud.pingwu.application.Cache;
import com.sctvcloud.pingwu.application.Constances;
import com.sctvcloud.pingwu.beans.CommentTemp;
import com.sctvcloud.pingwu.beans.FComment;
import com.sctvcloud.pingwu.beans.FocusColumn;
import com.sctvcloud.pingwu.http.AbsListNetCallback;
import com.sctvcloud.pingwu.http.NetUtils;
import com.sctvcloud.pingwu.ui.activities.RebllionCommitActivity;
import com.sctvcloud.pingwu.ui.dialog.CommentDiaFragment;
import com.sctvcloud.pingwu.ui.utils.CollectionUtils;
import com.sctvcloud.pingwu.ui.utils.KeyBoardUtils;
import com.sctvcloud.pingwu.ui.utils.SkipUtil;
import com.sctvcloud.pingwu.utils.ListTypeUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.Unbinder;

/**
 * The type Base detail activity.
 */
public class BaseDetailActivity extends BaseActivity {
    /**
     * The Share fragment.
     */
    protected ShareFragment shareFragment;
    /**
     * The constant SHARE_TAG.
     */
    public static final String SHARE_TAG = "share_fragment";

    /**
     * The constant COMMENT_TAG.
     */
    public static final String COMMENT_TAG = "dia_comment_fragment";

    /**
     * The Base url.
     */
    protected String baseUrl;

    private CommentTemp commentTemp;

    /**
     * The M handler.
     */
    protected Handler mHandler;

    private String newsId;
    private int typeName = 0;//新闻、直播类型

    /**
     * The Comment column.
     */
    protected FocusColumn commentColumn;

    /**
     * The Comment dia fragment.
     */
    protected CommentDiaFragment commentDiaFragment;

    /**
     * The Comment type.
     */
    protected int commentType;

    /**
     * The Butter unbinder.
     */
    protected Unbinder butterUnbinder;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        baseUrl = getIntent().getStringExtra(EX_URL);
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                if (msg != null) {
                    parseHanldeMsg(msg);
                }
            }
        };
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void onDestroy() {
        if (butterUnbinder != null) {
            butterUnbinder.unbind();
        }
        super.onDestroy();
        TimeObserve.removeObserS(getOwnerName() + SHARE_TAG, getOwnerName() + COMMENT_TAG);
    }

    @Override
    protected void onLoginUnSuc() {
        if (commentTemp != null) {
            toast(R.string.please_login_first);
            commentTemp = null;
        }
    }

    private CommentDiaFragment.SendComment sendComment = new CommentDiaFragment.SendComment() {
        @Override
        public boolean onCommentSendPrepare(int mode) {
            return onCommentNetPrepare(mode);
        }

        @Override
        public void onCommentSendSuccess(int mode) {
            SkipUtil.skipToAddUserOperate(BaseDetailActivity.this, getOwnerName(),   12, typeName, "提交评论成功", newsId, Cache.getInstance().getCurrentChannelId());
            addInvitation(Constances.ADD_INTEGRAL_COMMENT, false);
            onCommentSendSuc(mode);
        }

        @Override
        public void onCommentSendFinish(int mode, boolean isNetSuc) {

        }
    };

    /**
     * Parse hanlde msg.
     *
     * @param msg the msg
     */
    protected void parseHanldeMsg(@NonNull Message msg) {
    }

    protected void onLoginSuc() {
    }

    /**
     * Gets conmment send back msg.
     *
     * @param msg the msg
     */
    protected void getConmmentSendBackMsg(String msg) {
        KeyBoardUtils.closeKeyboard(this);
        if (!TextUtils.isEmpty(msg)) {
            toast("发送评论" + msg);
        }
    }
    protected synchronized void showShareFragment(final IShares iShares, final ShareFragment.OnShareFragmentClickListener onShareFragmentClickListener, final ShareFragment.ShareSuccess successListener) {
        initPermission();
//        if (shareFragment == null) {
        shareFragment = new ShareFragment();
//        }
//        if (shareFragment.isAdded() || TimeObserve.isEarlyS(getOwnerName() + SHARE_TAG, 50)) {
//            return;
//        }
        shareFragment.setShares(iShares);
        shareFragment.setOnShareFragmentClickListener(onShareFragmentClickListener);
//        shareFragment.setHide(true);

        shareFragment.setShareSuccessListener(new ShareFragment.ShareSuccess() {
            @Override
            public void OnShareSuccess(String shareType) {
                if (null != successListener) {
                    successListener.OnShareSuccess(shareType);
                } else {
                    addInvitation(Constances.ADD_INTEGRAL_FORWARD, false);
                    SkipUtil.skipToAddUserOperate(BaseDetailActivity.this, getOwnerName(), 14, typeName, shareType, newsId, Cache.getInstance().getCurrentChannelId());
                }
            }
        });

        FragmentManager fm = getSupportFragmentManager();
        shareFragment.show(fm, SHARE_TAG);
        fm.executePendingTransactions();
    }
    /**
     * Show share fragment.
     *
     * @param iShares                      the shares
     * @param onShareFragmentClickListener the on share fragment click listener
     */
    protected synchronized void showShareFragment(IShares iShares, ShareFragment.OnShareFragmentClickListener onShareFragmentClickListener) {
//        if (shareFragment == null) {
        shareFragment = new ShareFragment();
//        }
//        if (shareFragment.isAdded() || TimeObserve.isEarlyS(getOwnerName() + SHARE_TAG, 50)) {
//            return;
//        }
        shareFragment.setShares(iShares);
        shareFragment.setOnShareFragmentClickListener(onShareFragmentClickListener);
        shareFragment.setShareSuccessListener(new ShareFragment.ShareSuccess() {
            @Override
            public void OnShareSuccess(String shareType) {
                addInvitation(Constances.ADD_INTEGRAL_FORWARD, false);
                SkipUtil.skipToAddUserOperate(BaseDetailActivity.this, getOwnerName(),   14, typeName, shareType, newsId, Cache.getInstance().getCurrentChannelId());

            }
        });
        FragmentManager fm = getSupportFragmentManager();
        shareFragment.show(fm, SHARE_TAG);
        fm.executePendingTransactions();
    }

    /**
     * Gets comment news.
     *
     * @param id          the id
     * @param requestType the request type
     * @param capacity    the capacity
     * @param index       the index
     * @return the comment news
     */
    protected boolean getCommentNews(String id, int requestType, int capacity, int index) {
        if (!onCommentNetPrepare(Constances.MODE_COMMENT_GET_NEW)) {
            return false;
        }
        NetUtils.getNetAdapter().getCommentList(getOwnerName(), id, requestType, capacity, index
                , new AbsListNetCallback<FComment>(ListTypeUtils.FProgramme()) {
                    private boolean isSuc;

                    @Override
                    public void onSuc(List<FComment> fProgrammes) {
                        JLog.e("get comment suc\n  " + fProgrammes);
                        onCommentGetListSuc(getPageResponse().getData().getCommentCount(), fProgrammes);
                        isSuc = true;
                    }

                    @Override
                    public void onError(Throwable ex, String errorMsg) {
                        super.onError(ex, errorMsg);
                        JLog.e("===error==" + errorMsg);
                    }

                    @Override
                    public void onEnd() {
                        super.onEnd();
                        onCommentNetFinish(Constances.MODE_COMMENT_GET_NEW, isSuc);
                    }
                });
        return true;
    }

    /**
     * Gets comment news.
     *
     * @param id          the id
     * @param url         the url
     * @param requestType the request type
     * @param capacity    the capacity
     * @param index       the index
     * @return the comment news
     */
    protected boolean getCommentNews(String id, String url, int requestType, int capacity, int index) {
        if (!onCommentNetPrepare(Constances.MODE_COMMENT_GET_NEW)) {
            return false;
        }
        NetUtils.getNetAdapter().getCommentList(getOwnerName(), url + "getCommentList", id, requestType, capacity, index
                , new AbsListNetCallback<FComment>(ListTypeUtils.FProgramme()) {
                    private boolean isSuc;

                    @Override
                    public void onSuc(List<FComment> fProgrammes) {
                        JLog.e("get comment suc\n  " + fProgrammes);
                        onCommentGetListSuc(getPageResponse().getData().getCommentCount(), fProgrammes);
                        isSuc = true;
                    }

                    @Override
                    public void onError(Throwable ex, String errorMsg) {
                        super.onError(ex, errorMsg);
                        JLog.e("===error==" + errorMsg);
                    }

                    @Override
                    public void onEnd() {
                        super.onEnd();
                        onCommentNetFinish(Constances.MODE_COMMENT_GET_NEW, isSuc);
                    }
                });
        return true;
    }

    /**
     * On comment get list suc.
     *
     * @param count       the count
     * @param fProgrammes the f programmes
     */
    protected void onCommentGetListSuc(int count, List<FComment> fProgrammes) {
    }

    /**
     * On comment net finish.
     *
     * @param mode     the mode
     * @param isNetSuc the is net suc
     */
    protected void onCommentNetFinish(int mode, boolean isNetSuc) {
    }

    /**
     * On comment send suc.
     *
     * @param mode the mode
     */
    protected void onCommentSendSuc(int mode) {
    }

    /**
     * On comment net prepare boolean.
     *
     * @param mode the mode
     * @return the boolean
     */
    protected boolean onCommentNetPrepare(int mode) {
        return true;
    }

    /**
     * Show comment dialog.
     *
     * @param newsId    the news id
     * @param commentId the comment id
     * @param types     the types
     */
    protected synchronized void showCommentDialog(String newsId, String commentId, int types) {
        JLog.e("newsId =" + newsId + "   commentId=" + commentId);
        if (TextUtils.isEmpty(newsId)) {
            toast(R.string.data_wrong);
            return;
        }
        FragmentManager fm = getSupportFragmentManager();
//        if (commentDiaFragment == null) {
        commentDiaFragment = new CommentDiaFragment();
        commentDiaFragment.setSendComment(sendComment);
        commentDiaFragment.setCommentType(types);
        this.newsId = newsId;
//        }
//        if (commentDiaFragment.isAdded() || TimeObserve.isEarlyS(getOwnerName() + COMMENT_TAG, 50)) {
//            return;
//        }
        commentDiaFragment.setInfo(newsId, commentId);
        commentDiaFragment.setTypes(types);
        commentDiaFragment.show(fm, COMMENT_TAG);
        fm.executePendingTransactions();
    }

    /**
     * Show comment dialog.
     *
     * @param newsId    the news id
     * @param isLuzhou  the is luzhou
     * @param commentId the comment id
     * @param types     the types
     */
    protected synchronized void showCommentDialog(String newsId, boolean isLuzhou, String commentId, int types) {
        JLog.e("newsId =" + newsId + "   commentId=" + commentId);
        if (TextUtils.isEmpty(newsId)) {
            toast(R.string.data_wrong);
            return;
        }
        FragmentManager fm = getSupportFragmentManager();
//        if (commentDiaFragment == null) {
        commentDiaFragment = new CommentDiaFragment();
        commentDiaFragment.setSendComment(sendComment);
        commentDiaFragment.setLuzhow(isLuzhou);
        commentDiaFragment.setCommentType(types);
        this.newsId = newsId;
//        }
//        if (commentDiaFragment.isAdded() || TimeObserve.isEarlyS(getOwnerName() + COMMENT_TAG, 50)) {
//            return;
//        }
        commentDiaFragment.setInfo(newsId, commentId);
        commentDiaFragment.setTypes(types);
        commentDiaFragment.show(fm, COMMENT_TAG);
        fm.executePendingTransactions();
    }

    /**
     * Sets type name.
     *
     * @param typeName the type name
     */
    public void setTypeName(int typeName) {
        this.typeName = typeName;
    }

    /**
     * Sets news id.
     *
     * @param newsId the news id
     */
    public void setNewsId(String newsId) {
        this.newsId = newsId;
    }

    /**
     * Check collect.
     *
     * @param id the id
     */
    protected void checkCollect(String id) {
        if (TextUtils.isEmpty(id)) {
            onCollectCheckResult(-1);
            return;
        }
        new ResultAsyncTask<Integer>(id) {
            @Override
            protected Integer doInBackground(Void... params) {
                return CollectionUtils.getInstance().isCollected(logTag) ? 1 : 0;
            }

            @Override
            protected void onPostExecute(Integer aBoolean) {
                onCollectCheckResult(aBoolean);
            }
        }.ex();
    }

    /**
     * On collect check result.
     *
     * @param result the result
     */
    protected void onCollectCheckResult(int result) {
    }
    /**
     * 获取动态权限
     */
    private void initPermission() {
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP_MR1) {
            //超过Android大于5.1 （即6.0以上）版本需要申请权限
            int REQUEST_CODE_CONTACT = 101;
            String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE};
            //验证是否许可权限
            for (String str : permissions) {
                if (this.checkSelfPermission(str) != PackageManager.PERMISSION_GRANTED) {
                    //申请权限
                    this.requestPermissions(permissions, REQUEST_CODE_CONTACT);
                    return;
                }
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        // If request is cancelled, the result arrays are empty.
        if (grantResults.length > 0) {
            // permission was granted, yay! Do the
            // contacts-related task you need to do.
            //权限申请成功，初始化异常日志的打印，以及跳转到主页
            int result = 0;
            for (int i = 0; i < grantResults.length; i++) {
                result += grantResults[i];
            }
            if (result != 0) {
                Toast.makeText(this, "部分权限申请失败，无法正常使用，请重试", Toast.LENGTH_LONG).show();
            }
        } else {
            // permission denied, boo! Disable the
            // functionality that depends on this permission.
            Toast.makeText(this, "权限申请失败，无法正常使用，请重试", Toast.LENGTH_LONG).show();

        }
    }
}
